<?php

class Admin_AuthController extends Zend_Controller_Action {

    private $_auth;

    public function init() {
        $this->_auth = Zend_Auth::getInstance();
    }

    public function loginAction() {

        $users = new Default_Model_DbTable_Gebruiker();
        $form = $this->_helper->form('login');
        $this->view->form = $form;

        if($this->getRequest()->isPost()) {
            if($form->isValid($this->getRequest()->getPost())) {
                $data = $form->getValues();
                
                $auth = Zend_Auth::getInstance();
                $authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'gebruikers');
                $authAdapter->setIdentityColumn('username')
                        ->setCredentialColumn('password');

                if(strlen($data['password']) != 32){
                    $authAdapter->setCredentialTreatment('MD5(?)');
                }
                      
                $authAdapter->setIdentity($data['username'])
                        ->setCredential($data['password']);
                $result = $auth->authenticate($authAdapter);
                if($result->isValid()) {
                    $storage = new Zend_Auth_Storage_Session();
                    $storage->write($authAdapter->getResultRowObject());
                    return $this->_helper->redirector('index', 'index');
                } else {
                    $this->view->errorMessage = "Invalid username or password. Please try again.";
                }
            }
        }
    }

    public function logoutAction() {
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();

        $answers = new Zend_Session_Namespace('answers', true);

        $answers->answer = new stdClass();

        $module = $this->getRequest()->getModuleName();

        return $this->_redirect($module);

    }

    public function lostAction() {
        $form = $this->_helper->form('lost');
        
        if($this->getRequest()->isPost()) {
            if($form->isValid($this->getRequest()->getPost())) {


//                if(){
//                    $this->
//                }else{
//
//                    $form->getElement('username')->setValue(NULL);
//                    $form->getElement('email')->setValue(NULL);
//                }
            }
        }
        $this->view->form = $form;
    }


}



